package com.zigong.app.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.dialog.ShareFragment;
import com.ruihang.generalibrary.ui.util.ViewUtils;
import com.ruihang.generalibrary.ui.widget.CustomEXImageView;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.ui.widget.CustomLinearLayout;
import com.ruihang.generalibrary.utils.ListUtils;
import com.zigong.app.R;
import com.zigong.app.base.BaseActivity;
import com.zigong.app.base.BaseDetailActivity;
import com.zigong.app.application.Cache;
import com.zigong.app.beans.FCityState;
import com.zigong.app.beans.FOrganDetail;
import com.zigong.app.beans.FScribeState;
import com.zigong.app.beans.FUsers;
import com.zigong.app.beans.NewsItem;
import com.zigong.app.http.AbsListNetCallback;
import com.zigong.app.http.AbsNetCallBack;
import com.zigong.app.http.NetUtils;
import com.zigong.app.http.ParamsEditor;
import com.zigong.app.ui.adapter.CityStaHomepageAdapter;
import com.zigong.app.ui.fragment.CityStateFragment;
import com.zigong.app.ui.util.RBaseItemDecoration;
import com.zigong.app.ui.utils.GlideCircleTransform;
import com.zigong.app.ui.utils.GlideUtil;
import com.zigong.app.ui.utils.TitleUtils;
import com.zigong.app.utils.ListTypeUtils;
import com.zigong.app.utils.UserManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 市州媒体主页（市州媒体的相关新闻页）
 */
public class CityStaHomepageActivity extends BaseDetailActivity implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener
        , CanRefreshLayout.IScrollView {
    @BindView(R.id.city_sta_homepager_refreshLayout)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected CustomLinearLayout layout;
    @BindView(R.id.city_sta_home_page_icon)
    protected CustomEXImageView icon;
    @BindView(R.id.city_sta_home_page_hot)
    protected ImageView hot_icon;
    @BindView(R.id.city_sta_home_page_channelName)
    protected CustomFontTextView channelName;
    @BindView(R.id.city_sta_home_page_isSubscribe)
    protected CustomFontTextView status;
    @BindView(R.id.city_sta_home_page_list)
    protected RecyclerView video_list;
    private CityStaHomepageAdapter adapter;
    private LinearLayoutManager manager;
    private MotionEvent mCurrentMotion;
    private FOrganDetail detail;
    private int currentPage = 0;
    private int pageAll = 0;
    private String token = null;
    private String userId = null;
    private int types; //type 1 订阅 2取消订阅
    private static final int TO_CHOOSE_CITY = 1;
    public static final int REQUEST_CODE_LOGIN = 101;
    public static final String CHANNEL_SUBSCRIBE = "channel_isSubscribe";
    public static final String INIT_SUBSCRIBE = "init_isSubscribe";//是否需要初始化订阅状态
    public static final String HOT_TAG = "hot_tag";
    private String id, title, detailUrl;
    private boolean isSubscribe;
    private boolean isNeedInitSubscribe = false;
    private String lastChannelId = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this);
        lastChannelId = Cache.getInstance().getCurrentChannelId();
        String channelID  = Cache.getInstance().getCurrentColumnId("市州", "市州");
        Cache.getInstance().setCurrentChannelId(channelID);
        initView();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_city_sta_homepage);
        ButterKnife.bind(this);
    }

    private void initView() {
        ImageView logoImg = (ImageView) findViewById(R.id.title_top_logo);
//        if (null != logoImg) {
//            logoImg.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    Intent intent = new Intent(CityStaHomepageActivity.this, ChooseCityActivity.class);
//                    intent.putExtra(ChooseCityActivity.TITLE_KEY, Cache.getInstance().getChoosedCity());
//                    startActivityForResult(intent, TO_CHOOSE_CITY);
//                }
//            });
//        }
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        id = getIntent().getStringExtra(EX_ID);
        title = getIntent().getStringExtra(EX_TITLE);
        detailUrl = getIntent().getStringExtra(BaseActivity.EX_URL);
        isSubscribe = getIntent().getBooleanExtra(CHANNEL_SUBSCRIBE, false);
        isNeedInitSubscribe = getIntent().getBooleanExtra(INIT_SUBSCRIBE, false);
        String hotLevel = getIntent().getStringExtra(HOT_TAG);
        if (!TextUtils.isEmpty(hotLevel)) {
            if (hotLevel.equals("0")) {
                hot_icon.setImageResource(R.mipmap.icon_hot_high);
            } else if (hotLevel.equals("1")) {
                hot_icon.setImageResource(R.mipmap.icon_hot_mid);
            } else if (hotLevel.equals("2")) {
                hot_icon.setImageResource(R.mipmap.icon_hot_low);
            }
        }
        if (!TextUtils.isEmpty(title)) {
            channelName.setText(title);
        }
        getSubscribeState(isSubscribe);
        manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        video_list.setLayoutManager(manager);
        video_list.setItemAnimator(new DefaultItemAnimator());
        video_list.addItemDecoration(new RBaseItemDecoration(2));
        layout.setiScrollView(this);
        refreshLayout.autoRefresh();
        if (isNeedInitSubscribe) {
            getSubscribeList();
        }
    }

    @Override
    public void onRefresh() {
        currentPage = 0;
        getDetailList(currentPage);
    }

    @Override
    public void onLoadMore() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.loadMoreComplete();
        } else {
            currentPage = currentPage + 1;
            if (currentPage < pageAll) {
                getDetailList(currentPage);
            }
        }

    }

    /**
     * 获取市州媒体详情数据
     * @param calledPage
     */
    private void getDetailList(int calledPage) {
        if (TextUtils.isEmpty(detailUrl) || !detailUrl.endsWith(".json")) {
            toast("数据错误");
            return;
        }
        NetUtils.getNetAdapter().getOrganList(getOwnerName(), detailUrl, calledPage, new AbsNetCallBack<FOrganDetail>(FOrganDetail.class, calledPage) {
            @Override
            public void onSuc(FOrganDetail organDetal) {
                if (organDetal != null) {
                    detail = organDetal;
                    pageAll = organDetal.getPageAll();
                    currentPage = organDetal.getPageIndex();
                    setDetailData(organDetal);
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
                onNetFinish();
            }
        });
    }

    /**
     * 获取用户订阅的机构
     */
    private void getSubscribeList() {
        String token = "";
        String userId = "";
        if (UserManager.getInstance().isLogin()) {
            FUsers user = UserManager.getInstance().getUser();
            token = user.getToken();
            userId = user.getUserId();
        }
        if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(userId)) {
            ParamsEditor pe = new ParamsEditor();
            pe.put("userId", userId);
//            ArrayMap<String, Object> params = new ArrayMap<>();
//            params.put("token", token);
//            params.put("userId", userId);
            NetUtils.getNetAdapter().getUserOrganList(getOwnerName(), pe.getEncryptedParams(token)
                    , new AbsListNetCallback<FCityState>(ListTypeUtils.FCityState()) {
                        @Override
                        public void onSuc(List<FCityState> fCityStates) {
                            if (ListUtils.isListValued(fCityStates)) {
                                compareSubscribe(id, fCityStates);
                            }
                        }

                        @Override
                        public void onError(Throwable ex, String errorMsg) {
                            super.onError(ex, errorMsg);
//                            toast(errorMsg);
                        }
                    });
        } else {
            JLog.e("====" + "你还没有登录");
        }
    }

    /**
     * 对比那些机构已订阅，并刷新机构数据状态
     */
    private void compareSubscribe(String institutionId, List<FCityState> subList) {

        for (int j = 0; j < subList.size(); j++) {
            if (institutionId.equalsIgnoreCase(subList.get(j).getInstitutionId())) {
                getSubscribeState(true);
            }
        }
    }

    private synchronized void onNetFinish() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.refreshComplete();
        }
        if (refreshLayout.isLoading()) {
            refreshLayout.loadMoreComplete();
        }
        refreshLayout.setLoadMoreEnabled(currentPage + 1 < pageAll);
    }

    /**
     * 市州媒体订阅或取消订阅请求
     */
    private void getSubscribeStateChange() {
        if (UserManager.getInstance().isLogin()) {
            FUsers user = UserManager.getInstance().getUser();
            token = user.getToken();
            userId = user.getUserId();
            if (isSubscribe) {
                types = 2;
            } else {
                types = 1;
            }
//            ArrayMap<String, Object> params = new ArrayMap<>();
//            params.put("institutionId", id);
//            params.put("token", token);
//            params.put("type", types); //1订阅 2 取消订阅
//            params.put("userId", userId);
            ParamsEditor pe = new ParamsEditor();
//            pe.put("userId", userId);
//            ArrayMap<String, Object> params = new ArrayMap<>();
            pe.put("institutionId", id);
            pe.put("type", types); //1订阅 2 取消订阅
            pe.put("userId", userId);
            NetUtils.getNetAdapter().getSubscribeState(getOwnerName(), pe.getEncryptedParams(token)
                    , new AbsNetCallBack<FScribeState>(FScribeState.class) {
                        @Override
                        public void onSuc(FScribeState scribeState) {
                            isSubscribe = !isSubscribe;
                            getSubscribeState(isSubscribe);

                        }

                        @Override
                        public void onError(Throwable ex, String errorMsg) {
                            super.onError(ex, errorMsg);
                            JLog.e("====error=" + errorMsg);
                            toast(errorMsg);
                        }
                    });

        } else {
            Intent intent = new Intent(this, LoginActivity.class);
            startActivityForResult(intent, REQUEST_CODE_LOGIN);
        }

    }

    /**
     * 显示初始化市州媒体数据
     * @param detail
     */
    private void setDetailData(FOrganDetail detail) {
        if (pageAll == 0) {
            pageAll = detail.getPageAll();
        }
        initInfo(detail);
        List<NewsItem> dynamicList = detail.getDynamicList();
        if (ListUtils.isListValued(dynamicList)) {
            if (currentPage == 0) {
                if (adapter == null) {
                    adapter = new CityStaHomepageAdapter(this, dynamicList);
                    video_list.setAdapter(adapter);
                } else {
                    adapter.setData(dynamicList);
                }
            } else {
                adapter.addDatas(dynamicList);
            }

        }

    }

    private void initInfo(FOrganDetail detail) {
        String imgUrl = detail.getInstitutionImage();
        GlideUtil.getGlid(this, imgUrl).error(R.mipmap.icon_circle_avatar)
                .placeholder(R.mipmap.icon_circle_avatar).transform(new GlideCircleTransform(this))
                .into(icon);
    }

    /**
     * 显示订阅或未订阅
     * @param isSubscribe
     * @return
     */
    private boolean getSubscribeState(boolean isSubscribe) {
        status.setText(isSubscribe ? getString(R.string.city_state_subscribe) : getString(R.string.city_state_no_subscribe));
        status.setTextColor(isSubscribe ? getResources().getColor(R.color.white) : getResources().getColor(R.color.colorUpdate));
        status.setBackgroundResource(isSubscribe ? R.drawable.ucrop_bg_cv_red : R.drawable.bg_look_back);
        return isSubscribe;
    }

    @OnClick(value = {R.id.title_top_layout_back, R.id.title_top_layout_edit, R.id.city_sta_home_page_isSubscribe})
    public void ItemClcik(View v) {
        switch (v.getId()) {
            case R.id.title_top_layout_back:
                finish();
                break;
            case R.id.title_top_layout_edit:
                if (detail != null && !TextUtils.isEmpty(detail.getSharedUrl())) {
                    this.setNewsId(detail.getInstitutionId());
                    showShareFragment(detail, new ShareFragment.OnShareFragmentClickListener() {
                        @Override
                        public void onClick(Pair<String, String> pair) {
                            ArrayList<Pair<String, String>> pairs = new ArrayList<>();
                            pairs.add(new Pair<>("页面", "首页"));
                            pairs.add(new Pair<>("栏目", "市州"));
                            pairs.add(new Pair<>("位置", "专题名称"));
                            pairs.add(pair);
                            GridsumWebDissector.getInstance().trackEvent(CityStaHomepageActivity.this, "", title, "", 200, pairs);
                        }
                    });
                } else {
                    toast(R.string.share_data_wrong);
                }

                break;
            case R.id.city_sta_home_page_isSubscribe:
                getSubscribeStateChange();
                ArrayList<Pair<String, String>> pairs = new ArrayList<>();
                pairs.add(new Pair<>("页面", "首页"));
                pairs.add(new Pair<>("栏目", "市州"));
                pairs.add(new Pair<>("位置", "专题名称"));
                if (isSubscribe) {
                    pairs.add(new Pair<>("行为类型", "取消订阅"));
                } else {
                    pairs.add(new Pair<>("行为类型", "点击订阅"));
                }
                GridsumWebDissector.getInstance().trackEvent(CityStaHomepageActivity.this, "", title, "", 200, pairs);

                break;
        }
    }

    @Override
    public void onBackPressed() {
        setResultes();
        super.onBackPressed();
    }

    private void setResultes() {
        Intent intent = getIntent();
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Cache.getInstance().setCurrentChannelId(lastChannelId);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_LOGIN) {
            onRefresh();
        } else if (requestCode == TO_CHOOSE_CITY && resultCode == RESULT_OK) {
            finish();
        }
    }

    @Override
    public boolean canScrollUp(MotionEvent motionEvent) {
        if (video_list == null) {
            return false;
        }
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mCurrentMotion = MotionEvent.obtain(motionEvent);
                return canScrolledUp(motionEvent);
            case MotionEvent.ACTION_MOVE:
                if (mCurrentMotion != null) {
                    return canScrolledUp(mCurrentMotion);
                } else {
                    return canScrolledUp(motionEvent);
                }
            default:
                mCurrentMotion = null;
                return canScrolledUp(motionEvent);
        }
    }

    @Override
    public boolean canScrollDown(MotionEvent motionEvent) {
        if (video_list == null) {
            return false;
        }
        if (ViewUtils.isTouchPointInView(video_list, motionEvent.getRawX(), motionEvent.getRawY(), 0)) {
            return ViewCompat.canScrollVertically(video_list, 1);
        } else if (ViewUtils.isTouchPointInView(video_list, motionEvent.getRawX(), motionEvent.getRawY(), 0)) {
            return ViewCompat.canScrollVertically(video_list, 1);
        }
        return false;
    }

    private boolean canScrolledUp(MotionEvent me) {
        if (ViewUtils.isTouchPointInView(video_list, me.getRawX(), me.getRawY(), 0)) {
            return ViewCompat.canScrollVertically(video_list, -1);
        } else if (ViewUtils.isTouchPointInView(video_list, me.getRawX(), me.getRawY(), 0)) {
            return ViewCompat.canScrollVertically(video_list, -1);
        }
        return false;
    }

}
